package com.beiing.tianshuai.tianshuai.mine.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.UpdatePersonalInfoBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.PersonalInfoPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.PersonalInfoViewImpl;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomSingleCheckDialog;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PersonalInformationActivity extends BaseActivity implements PersonalInfoViewImpl {

    @BindView(R.id.et_user_email)
    EditText mEtUserEmail;
    @BindView(R.id.toolbar_navigation)
    ImageView mToolbarNavigation;                       // 返回
    @BindView(R.id.toolbar)
    Toolbar mToolbar;                                   // 返回
    @BindView(R.id.toolbar_save)
    TextView mToolbarSave;                              // 保存
    @BindView(R.id.civ_user_avatar)
    CircleImageView mCivUserAvatar;                     // 头像
    @BindView(R.id.rl_user_avatar)
    RelativeLayout mRlUserAvatar;                       // 头像
    @BindView(R.id.et_user_name)
    EditText mEtUserName;                               // 昵称
    @BindView(R.id.rl_user_sex)
    RelativeLayout mRlUserSex;                          // 性别
    @BindView(R.id.txt_user_sex)
    TextView mTxtUserSex;                               // 性别
    @BindView(R.id.et_user_tel)
    TextView mEtUserTel;                                // 手机号码
    @BindView(R.id.txt_user_university)
    EditText mEtUserUniversity;                         // 学校组织
    @BindView(R.id.txt_user_sign)
    EditText mEtUserSign;                               // 个性签名

    private String mPhoto;
    private String mName;
    private String mSex;
    private String mPhone;
    private String mUniversity;
    private String mSign;
    private String mEmail;
    private PersonalInfoPresenter mPresenter;
    private File mUpdateAvatar;
    private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
    private static final String TAG = "PersonalInformationActi";
    private boolean isChanged;
    private String mPhotoPath;
    private Context mContext;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_information;
    }

    @Override
    protected void init() {
        ButterKnife.bind(this);
        mContext = this;
        setSupportActionBar(mToolbar);
        initUserInfo();
        initListener();
        initPresenter();
    }

    // 初始化用户信息
    private void initUserInfo() {
        mPhoto = SPUtils.getString(mContext, "photo", "1.jpg");
        mName = SPUtils.getString(mContext, "name", "");
        mEmail = SPUtils.getString(mContext, "email", "");
        mSex = SPUtils.getString(mContext, "sex", "");
        mPhone = SPUtils.getString(mContext, "tel", "");
        mUniversity = SPUtils.getString(mContext, "unit", "");
        mSign = SPUtils.getString(mContext, "sign", "");
        RequestOptions requestOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .override(350, 350);
        Glide.with(mContext.getApplicationContext())
                .load(HttpRequestConstant.USER_PIC_HEAD + mPhoto)
                .apply(requestOptions)
                .into(mCivUserAvatar);
        mTxtUserSex.setText("1".equals(mSex) ? "男" : "女");
        mEtUserName.setText(mName);
        mEtUserTel.setText(mPhone);
        mEtUserUniversity.setText(mUniversity);
        mEtUserSign.setText(mSign);
        mEtUserEmail.setText(mEmail);
    }

    private void initListener() {
        // 昵称
        mEtUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!isChanged) {
                    isChanged = !mName.equals(editable.toString());
                }
            }
        });

        // 电话号
        mEtUserTel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!isChanged) {
                    isChanged = !mPhone.equals(editable.toString());
                }
            }
        });

        // 邮箱
        mEtUserEmail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!isChanged) {
                    isChanged = !mEmail.equals(editable.toString());
                }
            }
        });

        // 学院组织
        mEtUserUniversity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!isChanged) {
                    isChanged = !mUniversity.equals(editable.toString());
                }
            }
        });


        // 签名
        mEtUserSign.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!isChanged) {
                    isChanged = !mSign.equals(editable.toString());
                }
            }
        });

        // 性别
        mRlUserSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] items = new String[]{"男", "女"};
                final CustomSingleCheckDialog singleCheckDialog = new CustomSingleCheckDialog(mContext, R.style.dialog, items, "选择性别");
                singleCheckDialog.setOnItemClickListener(new CustomSingleCheckDialog.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        mTxtUserSex.setText(items[position]);
                        singleCheckDialog.dismiss();
                    }
                });
                singleCheckDialog.show();
            }
        });

        // 返回
        mToolbarNavigation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isChanged) {
                    CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "是否放弃对资料的修改？", new CustomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            if (confirm) {
                                dialog.dismiss();
                                finish();
                            } else {
                                dialog.dismiss();
                            }
                        }
                    }).setNegativeButton("取消").setPositiveButton("确认").setTitle("提示");
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.show();
                } else {
                    finish();
                }
            }
        });

        // 头像
        mRlUserAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkSelfPermission();
            }
        });

        // 保存
        mToolbarSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uid = UserInfoBean.getUid(mContext);
                String sex = mTxtUserSex.getText().toString();
                if ("男".equals(sex)) {
                    sex = "1";
                } else {
                    sex = "2";
                }
                String name = mEtUserName.getText().toString();
                String email = mEtUserEmail.getText().toString();
                String phone = mEtUserTel.getText().toString();
                String unit = mEtUserUniversity.getText().toString();
                String sign = mEtUserSign.getText().toString();
                mPresenter.getEditPersonalInfoResult(uid, name, sex, phone, unit, sign, email);
            }
        });
    }

    private void initPresenter() {
        mPresenter = new PersonalInfoPresenter(this);
    }

    @Override
    public void onBackPressed() {
        if (isChanged) {
            CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "是否放弃对资料的修改？", new CustomDialog.OnCloseListener() {
                @Override
                public void onClick(Dialog dialog, boolean confirm) {
                    if (confirm) {
                        dialog.dismiss();
                        finish();
                    } else {
                        dialog.dismiss();
                    }
                }
            }).setTitle("提示");
            dialog.setCanceledOnTouchOutside(true);
            dialog.show();
        } else {
            finish();
        }
    }

    // 动态权限申请
    private void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.i("需要授权", TAG);
            if (ActivityCompat.shouldShowRequestPermissionRationale(PersonalInformationActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                LogUtils.i("拒绝过了", TAG);
                // 提示用户如果想要正常使用，要手动去设置中授权。
                showShortText("请在 设置-应用管理 中开启此应用的储存授权。");
            } else {
                LogUtils.i("进行授权", TAG);
                ActivityCompat.requestPermissions(
                        PersonalInformationActivity.this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSIONS_REQUEST_READ_CONTACTS
                );
            }
        } else {
            LogUtils.i("不需要授权", TAG);
            // 进行正常操作
            selectImage();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtils.i("同意授权", TAG);
                // 进行正常操作。
                selectImage();
            } else {
                LogUtils.i("拒绝授权", TAG);
            }
        }
    }

    private void selectImage() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                LogUtils.i("----------------- 选图开始 -----------------", TAG);
            }

            @Override
            public void onSuccess(List<String> photoList) {
                mPhotoPath = photoList.get(0);
                LogUtils.i(photoList.toString(), TAG);
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(mPhotoPath).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        if (isSuccess) {
                            mUpdateAvatar = new File(outfile);
                            String uid = UserInfoBean.getUid(mContext);
                            mPresenter.getUpdateAvatarResult(uid, mUpdateAvatar);
                        } else {
                            showShortText("图片过大");
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                LogUtils.i("用户已取消", TAG);
            }

            @Override
            public void onFinish() {
                LogUtils.i("----------------- 选图结束 -----------------", TAG);
            }

            @Override
            public void onError() {
                LogUtils.e("----------------- 选图异常 -----------------", TAG);
            }
        };
        /*
         GalleryConfig galleryConfig = new GalleryConfig.Builder()
         .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
         .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
         .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
         .pathList(path)                                     // 记录已选的图片
         .multiSelect(false)                                 // 是否多选   默认：false
         .multiSelect(false, 9)                              // 配置是否多选的同时 配置多选数量   默认：false ， 9
         .maxSize(9)                                         // 配置多选时 的多选数量。    默认：9
         .crop(false)                                        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
         .crop(false, 1, 1, 500, 500)                        // 配置裁剪功能的参数，   默认裁剪比例 1:1
         .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
         .filePath("/Gallery/Pictures")                      // 图片存放路径
         .build();
         */
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                                 // 是否多选   默认：false
                .crop(true)                                         // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(PersonalInformationActivity.this);
    }

    /**
     * 点击editText外部时隐藏软键盘
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v != null ? v.getWindowToken() : null, 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "正在提交，请稍后...", false);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestSuccess(UpdatePersonalInfoBean bean) {
        if (bean.getCode() == 200) {
            showShortText("提交成功");
            finish();
        } else {
            showShortText("提交失败");
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showShortText("网络异常");
    }

    @Override
    public void UpdateAvatar(UpdatePersonalInfoBean bean) {
        if (bean.getCode() == 200) {
            showShortText("修改成功");
            RequestOptions options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .override(350, 350)
                    .centerCrop();
            Glide.with(mContext.getApplicationContext())
                    .load(mUpdateAvatar)
                    .apply(options)
                    .into(mCivUserAvatar);
        } else {
            showShortText("修改失败");
        }
    }
}
